import { CustomTableInterface } from '@/components/ProTable/interface';
import { PublicInterface } from '@/interface/public';

import { formOpen } from '@/utils/form';
import { useAddForm } from './use-addForm';
import { PermissionInterface } from '@/api/interface/auth/permission';

export function useDataGrid(proTableBox: PublicInterface.ProTableValue) {
  const { addForm, saveAddForm, treeObj, getAddFormChildren, changeActionType } = useAddForm(proTableBox);
  let dataGrid = reactive<CustomTableInterface>({
    initParam: {
      id: 0
    },
    expandRowKeys: [],
    // 表格配置项
    columns: [
      { prop: 'operation', label: 'operation', fixed: 'right', width: 160 },
      {
        prop: 'name',
        label: '权限名称',
        align: 'left',
        width: 220
      },
      {
        prop: 'actionType',
        label: '操作类型',
        enum: statusOperateType
      },
      {
        prop: 'sort',
        label: '排序'
      },
      {
        prop: 'apiUrl',
        label: '后端访问路径',
        width: 260
      },
      {
        prop: 'metaRole',
        label: '权限码',
        width: 160
      },
      {
        prop: 'status',
        label: '用户状态',
        tag: true,
        enum: statusEnableOrDisabled
      },
      {
        prop: 'path',
        label: '路由菜单',
        width: 220
      },
      {
        prop: 'pathName',
        label: '路由名称',
        width: 160
      },
      {
        prop: 'componentPath',
        label: '视图文件路径',
        width: 220
      },
      {
        prop: 'redirect',
        label: '重定向地址',
        width: 220
      },
      {
        prop: 'metaIcon',
        label: '图标',
        width: 160
      },
      {
        prop: 'metaTitle',
        label: '路由标题',
        width: 160
      },
      {
        prop: 'metaActiveMenu',
        label: '高亮的菜单',
        width: 160
      },
      {
        prop: 'metaIsLink',
        label: '路由外链地址',
        width: 160
      },
      {
        prop: 'metaIsFull',
        label: '全屏',
        enum: statusYesOrNo
      },
      {
        prop: 'metaIsHide',
        label: '是否在菜单中隐藏',
        width: 160,
        enum: statusYesOrNo
      },
      {
        prop: 'metaIsAffix',
        label: '固定在标签页',
        width: 160,
        enum: statusYesOrNo
      },
      {
        prop: 'metaIsKeepAlive',
        label: '路由是否缓存',
        width: 160,
        enum: statusYesOrNo
      },
      {
        prop: 'metaFlag',
        label: '其他标识'
      },

      {
        prop: 'remark',
        label: 'remark'
      }
    ],
    headButtonList: [
      {
        label: '新增权限',
        type: 'primary',
        icon: 'el-Plus',
        // permissionCode: 'p:auth:user:save',
        methods: async () => {
          const row: { actionType: PublicInterface.PublicType['permissionType'] } = {
            actionType: 'search'
          };
          formOpen(addForm, 'addNewUsers', row);
          getAddFormChildren();
          nextTick(() => {
            changeActionType();
          });
        }
      }
    ],
    rowButtonList: [
      {
        label: 'edit',
        type: 'primary',
        display: item => item.status !== BasicKey.DISABLE,
        methods: async row => {
          const params = { ...row };
          formOpen(addForm, '编辑权限', params);

          await getAddFormChildren();

          nextTick(() => {
            Object.assign(addForm.form, {
              apiUrl: treeGetValues(treeObj.apiTreeData, row.apiUrl)
            });

            changeActionType();
          });
        },
        attrs: {
          link: true
        }
      },
      {
        label: '追加',
        type: 'primary',
        display: item => item.status !== BasicKey.DISABLE,
        // permissionCode: 'p:auth:user:save',
        methods: async row => {
          const params = {
            pid: row.id
          };

          formOpen(addForm, '追加权限', params);

          await getAddFormChildren();
          nextTick(() => {
            changeActionType();
          });
        },
        attrs: {
          link: true
        }
      },
      {
        label: 'enable',
        type: 'primary',
        // permissionCode: 'p:auth:user:status',
        display: item => item.status !== BasicKey.ENABLE,
        methods: row => {
          const params = { id: row.id, status: BasicKey.ENABLE };
          useHandleData(
            permissionUpdateStatus,
            params,
            `${transitionLanguages('table', 'disabled')}【${row.username}】${transitionLanguages('table', 'user')}`,
            proTableBox.value?.getTableList
          );
        },
        attrs: {
          link: true
        }
      },
      {
        label: 'disabled',
        type: 'danger',
        display: item => item.status !== BasicKey.DISABLE,
        methods: row => {
          const params = { id: row.id, status: BasicKey.DISABLE };
          useHandleData(
            permissionUpdateStatus,
            params,
            `${transitionLanguages('table', 'disabled')}【${row.username}】${transitionLanguages('table', 'user')}`,
            proTableBox.value?.getTableList
          );
        },
        attrs: {
          link: true
        }
      },
      {
        label: '删除',
        type: 'danger',
        // icon: 'svg-del',
        // permissionCode: 'maintain:remove',
        // tooltip: '删除',
        display: row => row.status === BasicKey.ENABLE,
        methods: (row: PermissionInterface.ResList) => {
          const params = { id: row.id };
          useHandleData(permissionDeleteById, params, `删除 【${row.name}】权限`, proTableBox.value.getTableList);
        },
        attrs: {
          link: true
        }
      }
    ]
  });

  let unfoldTreeData = new Map();

  /**
   * 懒加载树结构
   */
  const load = (row: PermissionInterface.ResList, treeNode: PermissionInterface.ResList[], resolve) => {
    permissionFindByPid({ id: row.id }).then((data: PermissionInterface.ResList[]) => {
      data.forEach(item => {
        item.hasChildren = item.childrenNumber && item.childrenNumber !== 0;
      });
      // 记录展开的树（用于后续刷新对应数据）
      unfoldTreeData.set(row.id, { row, treeNode, resolve });
      resolve(data);
    });
  };

  /**
   * 展开 关闭子菜单
   */
  const expandChange = (row: PermissionInterface.ResList, flag: boolean) => {
    if (flag) {
      dataGrid.expandRowKeys.push(row.id);
    } else {
      dataGrid.expandRowKeys.splice(dataGrid.expandRowKeys.indexOf(row.id), 1);
    }
  };

  /**
   * 根据pid刷新树结构数据
   */
  const refreshTreeData = (pid: number) => {
    let { row, treeNode, resolve } = unfoldTreeData.get(pid);
    load(row, treeNode, resolve);
  };

  /**
   * 对显示的数据进行回调处理
   */
  const dataCallBack = (data: PermissionInterface.ResList[]) => {
    data.forEach(item => {
      item.hasChildren = item.childrenNumber && item.childrenNumber !== 0;
    });

    for (let id of dataGrid.expandRowKeys) {
      proTableBox.value.element.store.states.treeData.value[id].loaded = false;
      refreshTreeData(id);
    }

    return data;
  };

  return { dataGrid, dataCallBack, expandChange, load, addForm, saveAddForm };
}
